// 简单的事件总线实现
class EventBus {
  events: { [key: string]: Function[] };

  constructor() {
    this.events = {};
  }

  // 监听事件
  on(event: string, callback: Function) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(callback);
  }

  // 移除事件监听
  off(event: string, callback?: Function) {
    if (!this.events[event]) return;
    
    if (callback) {
      const index = this.events[event].indexOf(callback);
      if (index > -1) {
        this.events[event].splice(index, 1);
      }
    } else {
      // 如果没有指定回调函数，移除所有监听器
      this.events[event] = [];
    }
  }

  // 触发事件
  emit(event: string, ...args: any[]) {
    if (!this.events[event]) return;
    
    this.events[event].forEach(callback => {
      try {
        callback(...args);
      } catch (error) {
        console.error(`事件 ${event} 的回调函数执行出错:`, error);
      }
    });
  }

  // 只监听一次事件
  once(event: string, callback: Function) {
    const onceCallback = (...args: any[]) => {
      callback(...args);
      this.off(event, onceCallback);
    };
    this.on(event, onceCallback);
  }

  // 清除所有事件监听
  clear() {
    this.events = {};
  }
}

export default EventBus;